package www.study.chatgpt.api.job;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import www.study.chatgpt.api.ai.IOpenAI;
import www.study.chatgpt.api.zhihu.model.IZhiHuApi;
import www.study.chatgpt.api.zhihu.model.req.ReqData;
import www.study.chatgpt.api.zhihu.model.vo.Data;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Random;

public class ChatgptSchedule {
    private Logger logger = LoggerFactory.getLogger(ChatgptSchedule.class);

    @Value("${chatbot-api.cookie}")
    private String cookie;

    @Resource
    private IZhiHuApi zhiHuApi;
    @Resource
    private IOpenAI openAI;

    // 表达式：cron.qqe2.com
    @Scheduled(cron = "0/30 * * * * ?")
    public void run() {
        try {
            if (new Random().nextBoolean()) {
                logger.info("随机打烊中...");
                return;
            }

            GregorianCalendar calendar = new GregorianCalendar();
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            if (hour > 22 || hour < 7) {
                logger.info("打烊时间不工作，AI 下班了！");
                return;
            }

            // 1. 检索问题
            ReqData questions = zhiHuApi.queryQuestions(cookie);
            logger.info("检索结果：{}", JSON.toJSONString(questions));
            List<Data> topics = questions.getData();
            if (null == topics || topics.isEmpty()) {
                logger.info("本次检索未查询到待会答问题");
                return;
            }

            // 2. AI 回答
            Data topic = topics.get(0);
            String answer = openAI.doChatGPT(topic.getQuestion().getTitle().trim());
            // 3. 问题回复
            boolean status = zhiHuApi.answer(topic.getQuestion().getId(), cookie, answer);
            logger.info("编号：{} 问题：{} 回答：{} 状态：{}", topic.getQuestion().getId(), topic.getQuestion().getTitle(), answer, status);
        } catch (Exception e) {
            logger.error("自动回答问题异常", e);
        }
    }

}
